
package com.scalar.chiptrack.finance.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;
import org.apache.poi.ss.usermodel.Workbook;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.finance.ProcessStepCostInfo;
import com.scalar.chiptrack.finance.forms.UpdateViewCostForm;
import com.scalar.chiptrack.finance.dao.UpdateViewCostDAO;
import com.scalar.chiptrack.operations.process.ChiptrackProduct;
import com.scalar.chiptrack.operations.process.dao.BomPartEntryDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;

import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;
import com.scalar.chiptrack.utils.ConfigManager;

public final class UpdateViewCostAction extends ChipTrackAction 
{

    private static final String ACTION_NAME = "/updateViewCost.do";
    public ActionForward execute (ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
                              throws Exception {

        String retval = "failure";
        HashMap<String,String> errors = new HashMap<String,String>();
		HashMap<String,String> info = new HashMap<String,String>();
        String action = request.getParameter ("action");
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        UpdateViewCostForm updateViewCostForm = (UpdateViewCostForm) form;
		String years = StringUtils.formatDateToString(new Date(), "yyyy");
		if ( action == null )
		{
			action = "";
		}
        Workbook workbook = null;
        String fileName = "";
        
		if ( action.equals("") || action.equalsIgnoreCase ("search") || action.equalsIgnoreCase("update") || action.equalsIgnoreCase("allowupdate")
                || action.equalsIgnoreCase("view") || "updateAllCurrentQuarterValues".equalsIgnoreCase( action )
                || "prjallowupdate".equalsIgnoreCase (action) || "prjview".equalsIgnoreCase (action) )
		{
            ArrayList<LabelValueBean> marketingProductList = ProductDao.loadAllBaseProducts( null );
            marketingProductList.add( new LabelValueBean( "-----BOM------","" ) );
            marketingProductList.addAll( BomPartEntryDAO.loadBomParts() );
			if ((marketingProductList == null) || (marketingProductList.isEmpty() == true)) {
				errors.put("No Products Found", null);
				request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
			}
			if ( errors.size() == 0 || errors.isEmpty() == true )
			{
				ArrayList<LabelValueBean> finalMktProdList = new ArrayList<LabelValueBean>();
				finalMktProdList.add(new LabelValueBean ("---- CHIPS -----", "0"));
                finalMktProdList.addAll( marketingProductList );
				request.setAttribute ("finalMktProdList", finalMktProdList);
				request.setAttribute ( "yearList", returnYearList() );
			}
		}
		if ( action.equals ("") )
		{
			updateViewCostForm.setProductId(-1);
			updateViewCostForm.setProdName ("");
			updateViewCostForm.setDateYear ( Integer.parseInt (years));
			return (mapping.findForward ("success"));
		}

		if ( action.equalsIgnoreCase ( "search" ) )
		{
			try
			{
                ArrayList<ChiptrackProduct> marketingProductList = new ArrayList<ChiptrackProduct>();

                if (  updateViewCostForm.getProductId() > 0 )
                {
                    marketingProductList = UpdateViewCostDAO.getProductNameList( null , updateViewCostForm.getProductId() );
                }

                if ( marketingProductList != null && marketingProductList.size() > 0 )
                {
                    request.setAttribute ("marketingProductList", marketingProductList);
                }
                else
                {
                    errors.put("No matching records found", null);
                    request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                }
                request.setAttribute( "action", action );
                request.setAttribute( "dateYear", ""+updateViewCostForm.getDateYear() );

                retval = "success";
			}
			catch (ScalarException se)
			{
				errors.put( ERROR_INTERNAL_SERVER_ERROR , ERROR_IN_LOAD_MARKETING_PRODUCTS );
				errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
			}
			return ( mapping.findForward ( retval ) );
		}

        if ( "allowupdate".equalsIgnoreCase (action) || "view".equalsIgnoreCase (action)
                || "prjallowupdate".equalsIgnoreCase (action) || "prjview".equalsIgnoreCase (action) )
        {

            int productId = -1;
            try
            {
                productId = Integer.parseInt( request.getParameter( "productId" ) );
				String dateYr = request.getParameter( "dateYear" );
				if ( dateYr != null && dateYr.trim().length() > 0 )
				{
					updateViewCostForm.setDateYear( Integer.parseInt( request.getParameter( "dateYear" ).trim() ) );
				}
				else
				{
					updateViewCostForm.setDateYear ( Integer.parseInt ( years.trim() ) );
				}
            }
            catch ( NumberFormatException nfe )
			{
                // Invalid or No product ID
            }
            if ("prjallowupdate".equalsIgnoreCase (action) || "prjview".equalsIgnoreCase (action) )
            {
                request.setAttribute ("prjaction", "true");
            }
            else
            {
                request.setAttribute ("prjaction", "false");
            }
            ArrayList<ProcessStepCostInfo> costList = null;
            if ( ConfigManager.isShowUpdateViewCostByLocation() )
            {
			    costList = UpdateViewCostDAO.loadProcessStepCostByProductIdLocation ( productId, updateViewCostForm.getDateYear() );
            }
            else
            {
                costList = UpdateViewCostDAO.loadProcessStepCostByProductId ( productId, updateViewCostForm.getDateYear() );
            }
            if ( costList != null && costList.size() > 0 )
            {
                updateViewCostForm.setCostList( costList );
                updateViewCostForm.setProductId( productId );
                updateViewCostForm.setProductName( request.getParameter ("productName") );

                request.setAttribute ("action", action);
                return (mapping.findForward ("showCostInfo"));
            }
            else
            {
                errors.put("For this Base Product, No Part Numbers are found", null);
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

                ArrayList<ChiptrackProduct> marketingProductList = new ArrayList<ChiptrackProduct>();
                if ( productId > 0 )
                {
                    marketingProductList = UpdateViewCostDAO.getProductNameList( null , productId );

                    request.setAttribute ("marketingProductList", marketingProductList);
                }
                updateViewCostForm.setProductId(-1);
                updateViewCostForm.setProdName ("");
                updateViewCostForm.setDateYear ( Integer.parseInt (years));
				request.setAttribute( "dateYear", ""+updateViewCostForm.getDateYear() );
                return (mapping.findForward ("success"));
            }
        }

        if ("update".equalsIgnoreCase (action))
        {
            boolean success = false;
         	try
			{
                String costType = request.getParameter ("costType");

                if( updateViewCostForm.getCostList() != null )
                {
                    if ( ConfigManager.isShowUpdateViewCostByLocation() )
                    {
                        UpdateViewCostDAO.updateProcessStepCostByLocation ( updateViewCostForm.getCostList(), updateViewCostForm.getDateYear() , costType);
                    }
                    else
                    {
                        UpdateViewCostDAO.updateProcessStepCost ( updateViewCostForm.getCostList(), updateViewCostForm.getDateYear(), costType);
                    }
                    success = true;
                    retval = "success";
                }
			}
			catch (ScalarException se)
			{
				errors.put ("Couldnt update Process Step cost information for the part number "+updateViewCostForm.getProductName(), null);
				se.printStackTrace();
				request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
			}

            if ( success )
            {
				info.put ("Process steps cost for the part number "+updateViewCostForm.getProductName()+" have been updated successfully", null);
				request.setAttribute (SessionKeys.INFO_MESSAGES, info);
				updateViewCostForm.setProductName( "" );
				updateViewCostForm.setProdName ("");
				updateViewCostForm.setCostList(null);
				updateViewCostForm.setProductId(-1);
				updateViewCostForm.setDateYear ( Integer.parseInt (years));
                return (mapping.findForward (retval));
            }
            else
            {
                updateViewCostForm.setProductName( "" );
				updateViewCostForm.setProdName ("");
				updateViewCostForm.setCostList(null);
				updateViewCostForm.setProductId(-1);
				updateViewCostForm.setDateYear ( Integer.parseInt (years));
				return (mapping.findForward (retval));
            }
        }

        if ("exportToExcel".equalsIgnoreCase( action ) )
        {
            int productId = -1;
            try
            {
                productId = Integer.parseInt( request.getParameter( "productId" ) );
				String dateYr = request.getParameter( "dateYear" );

				if ( dateYr != null && dateYr.trim().length() > 0 )
				{
					updateViewCostForm.setDateYear( Integer.parseInt( dateYr.trim() ) );
				}
				else
				{
					updateViewCostForm.setDateYear ( Integer.parseInt ( years.trim() ) );
				}
            }
            catch ( NumberFormatException nfe )
			{
                // Invalid or No product ID
            }

             String costType = request.getParameter ("costType");
            ArrayList reportList = null;
            if ( ConfigManager.isShowUpdateViewCostByLocation() )
            {
			    reportList = UpdateViewCostDAO.loadCostDetailsByProductIdByLocation ( productId, updateViewCostForm.getDateYear(), costType );
            }
            else
            {
                reportList = UpdateViewCostDAO.loadCostDetailsByProductId ( productId, updateViewCostForm.getDateYear(), costType );
            }

            workbook =  DataDumpReportsHelper.getWorkbook( reportList, updateViewCostForm.getDateYear() + " "+ costType +" Yield & Cost Report", null,null, null );

            fileName = updateViewCostForm.getDateYear() + " "+ costType +" Yield & Cost Report-" + DateUtil.getTimeStamp() ;

            //To GENERATE THE EXCEL REPORT
            ExcelUtils.generateExcelReport( workbook, fileName, response );

            return( mapping.findForward( "showCostInfo" ) );
        }
        if ( "updateCurrentQuarterValuesByProduct".equalsIgnoreCase( action ) )
        {
            request.setAttribute ("action", "allowupdate");
            try
            {
                UpdateViewCostDAO.updateCurrentQuarterValues( null, updateViewCostForm.getProductId() );
                info.put( "Current quarter values updated successfully", null );
            }
            catch ( Exception e )
            {
                errors.put ( "Could not update the current quarter values", null );
            }
            ArrayList<ProcessStepCostInfo> costList = null;
            if (ConfigManager.isShowUpdateViewCostByLocation() )
            {
                costList = UpdateViewCostDAO.loadProcessStepCostByProductIdLocation ( updateViewCostForm.getProductId(), updateViewCostForm.getDateYear() );
            }
            else
            {
                costList = UpdateViewCostDAO.loadProcessStepCostByProductId ( updateViewCostForm.getProductId(), updateViewCostForm.getDateYear() );
            }
            updateViewCostForm.setCostList( costList );
            
            request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            request.setAttribute (SessionKeys.INFO_MESSAGES, info);
            return (mapping.findForward ("showCostInfo"));
        }
        if ( "updateAllCurrentQuarterValues".equalsIgnoreCase( action ) ) //For all the base products
        {
            try
            {
                UpdateViewCostDAO.updateCurrentQuarterValues( null, 0 );
                info.put( "Current quarter values updated for all the products successfully", null );
            }
            catch ( Exception e )
            {
                errors.put ( "Could not update the current quarter values for all the products", null );
            }

            request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            request.setAttribute (SessionKeys.INFO_MESSAGES, info);
            return (mapping.findForward ("success"));
        }

        return (mapping.findForward (retval));
    }

	private ArrayList<LabelValueBean> returnYearList()
	{
		ArrayList<LabelValueBean> yearList = new ArrayList<LabelValueBean>();
		for ( int i = 2000 ; i < 2048; i++ )
		{
			yearList.add ( new LabelValueBean( ""+i, ""+i ) );
		}
		return yearList;
	}
}

